import redis
import time
import uuid
from rest_framework.response import Response

class RedisDistributedLock:
    def __init__(self, redis_client, lock_prefix, category_id, retry_count=3, retry_delay=0.1, lock_timeout=10):
        self.redis_client = redis_client
        self.lock_key = f"{lock_prefix}:{category_id}"
        self.lock_value = str(uuid.uuid4())
        self.retry_count = retry_count
        self.retry_delay = retry_delay
        self.lock_timeout = lock_timeout
        self.lock_acquired = False

    def acquire_lock(self):
        """尝试加锁，返回是否成功"""
        for _ in range(self.retry_count):
            self.lock_acquired = self.redis_client.set(
                self.lock_key, self.lock_value, ex=self.lock_timeout, nx=True
            )
            if self.lock_acquired:
                return True
            time.sleep(self.retry_delay)
        return False

    def release_lock(self):
        """释放锁（验证 value，防止误删）"""
        if self.lock_acquired:
            current_value = self.redis_client.get(self.lock_key)
            if current_value == self.lock_value:
                self.redis_client.delete(self.lock_key)

    def handle_lock(self):
        """封装加锁逻辑，返回 Response 或 None"""
        if not self.acquire_lock():
            return Response(
                {'code': 503, 'error': '系统繁忙，请稍后重试'},
                status=503
            )
        return None